import sys,os
import time
import cv2
import numpy as np
import pyautogui
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout,QWidget, QLabel, QLineEdit, QPushButton,QComboBox,QTextBrowser
from PySide6.QtCore import QTimer,Qt
from PySide6.QtGui import QIcon

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("网页监控工具")
        self.setWindowIcon(QIcon("shubiao.jpg"))
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.resize(300, 200)
        self.move(20, 20)

        self.cnt = 0
        self.totalcnt = 0
        self.flag = 0

        # 创建主窗口布局
        self.central_widget = QWidget()
        self.layout = QVBoxLayout(self.central_widget)
        self.pathlayout1 = QHBoxLayout()

        # 输入监控周期
        self.zhouqilayout = QHBoxLayout()
        self.label_interval = QLabel("监控间隔（秒）：")
        self.zhouqilayout.addWidget(self.label_interval,0)
        self.edit_interval = QLineEdit()
        self.edit_interval.setText("10")
        self.zhouqilayout.addWidget(self.edit_interval,1)
        self.layout.addLayout(self.zhouqilayout)

        # 开始监控按钮
        self.btn_start = QPushButton("开始监控")
        self.btn_start.clicked.connect(self.start_monitoring)
        self.layout.addWidget(self.btn_start)
        self.setCentralWidget(self.central_widget)

        # 显示当前屏幕截图
        self.nextlabel1 = QLabel("👇下一步")
        self.nextlabel1.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.nextlabel1)

        # 1、课程标志：
        self.kechenglayout = QHBoxLayout()
        self.label_target = QLabel("1、课程标志：")
        self.kechenglayout.addWidget(self.label_target,0)

        self.folder_path = "./imgnext"
        allowed_suffixes = ['.jpg', '.bmp', '.png', '.jpeg']
        self.selectPath = QComboBox() 
        self.kechenglayout.addWidget(self.selectPath,1)
        for filename in os.listdir(self.folder_path):
            file_path = os.path.join(self.folder_path, filename)
            if os.path.isfile(file_path) and filename.endswith(tuple(allowed_suffixes)):  # 确保是图片文件
                self.selectPath.addItem(file_path)
                self.totalcnt += 1
        self.layout.addLayout(self.kechenglayout)

        # 显示当前屏幕截图
        self.nextlabel2 = QLabel("👇下一步")
        self.nextlabel2.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.nextlabel2)

        self.label_target1 = QLabel("2、播放标志：")
        self.pathlayout1.addWidget(self.label_target1)
        self.edit_target1 = QLineEdit()
        self.edit_target1.setText("./queren\start.png")
        self.pathlayout1.addWidget(self.edit_target1)
        self.layout.addLayout(self.pathlayout1)

        # 显示当前屏幕截图
        self.nextlabel3 = QLabel("👇下一步")
        self.nextlabel3.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.nextlabel3)

        self.querenlayout = QHBoxLayout()
        self.label_queren = QLabel("3、检测播放确认标志：")
        self.querenlayout.addWidget(self.label_queren,0)
        self.edit_queren = QLineEdit()
        self.edit_queren.setText("./queren\queren.png")
        self.querenlayout.addWidget(self.edit_queren,1)
        self.layout.addLayout(self.querenlayout)

        # 显示当前屏幕截图
        self.nextlabel3 = QLabel("👇下一步")
        self.nextlabel3.setAlignment(Qt.AlignCenter)
        self.layout.addWidget(self.nextlabel3)

        self.jieshulayout = QHBoxLayout()
        self.label_jiesu = QLabel("4、课程结束标志：")
        self.jieshulayout.addWidget(self.label_jiesu,0)
        self.edit_jiesu = QLineEdit()
        self.edit_jiesu.setText("./queren\jiesu.png")
        self.jieshulayout.addWidget(self.edit_jiesu,1)
        self.layout.addLayout(self.jieshulayout)


        self.outputField = QTextBrowser()
        self.layout.addWidget(self.outputField,1)

        # 初始化定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.capture_and_click)

    def start_monitoring(self):
        self.cnt = 0
        self.flag = 0
        interval = self.edit_interval.text()
        target = self.selectPath.currentText()   # 获取目标文字或模板路径

        if not interval or not target:
            self.outputField.append("请输入监控间隔和目标文字或模板路径！")
            return

        try:
            interval = int(interval)
        except ValueError:
            self.outputField.append("监控间隔必须是整数！")
            return

        self.timer.start(interval * 1000)  # TimeInterval in milliseconds
        self.outputField.append(f"开始监控，间隔为 {interval} 秒")
        #self.capture_and_click()

    def capture_and_click(self):
        # 截取屏幕
        screenshot = pyautogui.screenshot()
        frame = np.array(screenshot)
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

        self.selectPath.setCurrentIndex(self.cnt)

        # 获取目标文字或模板路径
        target = self.selectPath.currentText()
        
        # 将目标文字转换为模板
        template = cv2.imread(target, cv2.IMREAD_COLOR)

        if template is None:
            self.outputField.append("无法加载目标模板，请检查路径！")
            return

        # 模板匹配
        result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

        # 如果匹配度足够高，则单击目标位置
        if max_val > 0.7 and self.flag == 0:  # 匹配度阈值
            x, y = max_loc
            x += template.shape[1] // 2
            y += template.shape[0] // 2
            pyautogui.moveTo(x, y, duration=0.2)
            pyautogui.click()
            self.outputField.append("已单击目标文字或区域1！")
            self.flag = 1
            time.sleep(2)
        

        screenshot1 = pyautogui.screenshot()
        frame1 = np.array(screenshot1)
        frame1 = cv2.cvtColor(frame1, cv2.COLOR_RGB2BGR)
        target1 = self.edit_target1.text()

        # 将目标文字转换为模板
        template1 = cv2.imread(target1, cv2.IMREAD_COLOR)

        if template1 is None:
            self.outputField.append("无法加载目标模板，请检查路径！")
            return

        result1 = cv2.matchTemplate(frame1, template1, cv2.TM_CCOEFF_NORMED)
        min_val1, max_val1, min_loc1, max_loc1 = cv2.minMaxLoc(result1)

        # 如果匹配度足够高，则单击目标位置
        if max_val1 > 0.6 and self.flag == 1:  # 匹配度阈值
            x, y = max_loc1
            x += template1.shape[1] // 2
            y += template1.shape[0] // 2
            pyautogui.moveTo(x, y, duration=0.2)
            pyautogui.click()
            self.outputField.append("已单击目标文字或区域2！")
            time.sleep(2)



        screenshot2 = pyautogui.screenshot()
        frame2 = np.array(screenshot2)
        frame2 = cv2.cvtColor(frame2, cv2.COLOR_RGB2BGR)
        target2 = self.edit_queren.text()

        # 将目标文字转换为模板
        template2 = cv2.imread(target2, cv2.IMREAD_COLOR)

        if template2 is None:
            self.outputField.append("无法加载目标模板，请检查路径！")
            return

        result2 = cv2.matchTemplate(frame2, template2, cv2.TM_CCOEFF_NORMED)
        min_val2, max_val2, min_loc2, max_loc2 = cv2.minMaxLoc(result2)

        # 如果匹配度足够高，则单击目标位置
        if max_val2 > 0.7 and self.flag == 1:  # 匹配度阈值
            x, y = max_loc2
            x += template2.shape[1] // 2
            y += template2.shape[0] // 2
            pyautogui.moveTo(x, y, duration=0.2)
            pyautogui.click()
            self.outputField.append("已单击目标文字或区域3！")
            time.sleep(2)

        screenshot3 = pyautogui.screenshot()
        frame3 = np.array(screenshot3)
        frame3 = cv2.cvtColor(frame3, cv2.COLOR_RGB2BGR)
        target3 = self.edit_jiesu.text()

        # 将目标文字转换为模板
        template3 = cv2.imread(target3, cv2.IMREAD_COLOR)
        if template3 is None:
            self.outputField.append("无法加载目标模板，请检查路径！")
            return
        
        result3 = cv2.matchTemplate(frame3, template3, cv2.TM_CCOEFF_NORMED)
        min_val3, max_val3, min_loc3, max_loc3 = cv2.minMaxLoc(result3)
        if max_val3 > 0.7 and self.flag == 1:
            self.outputField.append("jiesu!")
            self.cnt +=1
            self.flag = 0

        
        if self.cnt >= self.totalcnt:
            self.timer.stop()
            self.cnt = 0
            self.outputField.append("结束监控！")
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
